//
//  ProductViewContent.m
//  cutter
//
//  Created by mac on 15/12/21.
//  Copyright © 2015年 e360. All rights reserved.
//
#import "UserCenterPick.h"
#import "ProductCenterCtrl.h"
#import "ProductDetailCtrl.h"
#import "SpaceViewController.h"

//

#pragma mark -
#pragma mark ProductAssetsCtrl
@implementation ProductAssetsCtrl
- (void)viewDidLoad{
    [super viewDidLoad];
    //
    [self.deleteView setHidden:YES];
    [self.deleteView addTarget:self action:@selector(deleteTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.editView addTarget:self action:@selector(editTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.collectionView setAllowsMultipleSelection:YES];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.data count] + 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == 0) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"addIdentifier" forIndexPath:indexPath];
        return cell;
    }
    //
    id item = [self.data objectAtIndex:indexPath.item - 1];
    ProductCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    [cell.titieView setText:[AppData objToString:[item objectForKey:@"productname"] lable:nil]];
    [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
    [AppData loadImage:[item objectForKey:@"thumb400_jpg"] view:cell.imageView];
    [cell setType:self.type];
    return cell;
}
- (IBAction)exitTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, self.data);
    }else{
        if (self.navigationController) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(nullable id)sender{
    if (self.editView.selected) {
        return NO;
    }
    return YES;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __weak ProductAssetsCtrl *this = self;
    //
    
    ProductCenterCtrl *product = segue.destinationViewController;
    if ([product isKindOfClass:ProductCenterCtrl.class]) {
        [product setType:1];
        [product setOnSelected:^(id sender, id result){
            if (result) {
                [this.data addObject:result];
                [this.collectionView reloadData];
            }
            [this dismissViewControllerAnimated:YES completion:nil];
        }];
    }
    //
    if ([segue.destinationViewController isKindOfClass:ProductDetailCtrl.class]) {
        UIViewController *ctrl = segue.destinationViewController;
        if ([ctrl isKindOfClass:ProductDetailCtrl.class]) {
            NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
            if (indexPath) {
                //ProductDetailCtrl *ctrl = segue.destinationViewController;
                //[ctrl setData:[self.data objectAtIndex:indexPath.row-1]];
            }
        }
    }
}
- (void)editTouch:(UIButton*)sender{
    [sender setSelected:!sender.selected];
    [self.deleteView setHidden:!sender.selected];
    //
    NSArray *cells = [self.collectionView visibleCells];
    for (ProductCenterCell *cell in cells) {
        if ([cell isKindOfClass:ProductCenterCell.class]) {
            [cell.selectView setHidden:!sender.selected];
        }
    }
}
- (void)deleteTouch:(UIButton*)sender{
    NSArray *indexPaths = [self.collectionView indexPathsForSelectedItems];
    if ([indexPaths count] > 0) {
        for (NSIndexPath *indexPath in indexPaths.reverseObjectEnumerator) {
            id item = [self.data objectAtIndex:indexPath.item-1];
            [self.data removeObject:item];
        }
        [self.collectionView deleteItemsAtIndexPaths:indexPaths];
    }
    [self editTouch:self.editView];
}
@end


#pragma mark -
#pragma mark ProductFavoriteCtrl
@implementation ProductFavoriteCtrl
- (void)viewDidLoad{
    [super viewDidLoad];
    //
    [self.collectionView.headerView addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.headerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.headerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.headerView setTitle:@"下拉刷新" forState:TMRefreshStateNormal];
    //
    [self headerRefresh:nil];
}
-(void)reloadData{
    [self headerRefresh:nil];
}
- (void)headerRefresh:(TMRefresh*)sender{
    if (sender == nil) {
        sender = self.collectionView.headerView;
        [sender beginRefreshing];
    }
    //
    __weak ProductFavoriteCtrl *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this setData:[AppData userFavorite:this.condition]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender endRefreshing];
            [this.collectionView reloadData];
        });
    });
}
- (NSMutableDictionary *)condition{
    if (_condition == nil) {
        [self setCondition:[NSMutableDictionary dictionary]];
    }
    [_condition setValue:@(50) forKey:@"limit"];
    [_condition setValue:@"product" forKey:@"t"];
    return _condition;
}
//
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.data count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *item = [self.data objectAtIndex:indexPath.item];
    ProductCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
    [cell.titieView setText:[AppData objToString:[item objectForKey:@"productname"] lable:nil]];
    [AppData loadImage:[item objectForKey:@"pic"] view:cell.imageView];
    [cell setType:self.type];
    return cell;
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if(self.type == 2 && [sender isKindOfClass:UICollectionViewCell.class]){
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
        if (indexPath && self.onSelected){
            self.onSelected(self, [self.data objectAtIndex:indexPath.item]);
        }
        return NO;
    }
    return YES;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:ProductSynopsisCtrl.class]) {
            UICollectionViewCell *cell = [self findCell:sender];
            if (cell) {
                NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
                if (cell) {
                    ProductSynopsisCtrl *root = [ctrl.viewControllers firstObject];
                    [root setData:[self.data objectAtIndex:indexPath.item]];
                }
            }
        }
    }
}
-(id)findCell:(UIView*)sender{
    while (sender) {
        if ([sender isKindOfClass:UICollectionViewCell.class]) {
            return sender;
        }
        sender = sender.superview;
    }
    return nil;
}
- (IBAction)exitTouch:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
@end


#pragma mark -
#pragma mark ProductListsCtrl
@interface ProductListCtrlCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *nameView;
@property (weak, nonatomic) IBOutlet UILabel *sizeView;
@property (weak, nonatomic) IBOutlet UILabel *otherView;
@property (weak, nonatomic) IBOutlet UILabel *priceView;
@property (weak, nonatomic) IBOutlet UILabel *countView;
@end
@implementation ProductListCtrlCell
@end
@implementation ProductListCtrl
- (void)viewDidLoad {
    [self.view setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.3]];
    [self.rightLayout setConstant:-334];
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];
    [self.view setAlpha:0];
    //
    [UIView beginAnimations:nil context:nil];
    [self.view setAlpha:1];
    [UIView commitAnimations];
}
-(void)reloadData{
    CGFloat price = 0;
    NSInteger count = 0;
    for (id item in self.data) {
        NSInteger c = [[item objectForKey:@"count"] integerValue];
        CGFloat p = [[item objectForKey:@"price"] floatValue];
        price += p * c;
        count += c;
    }
    //
    NSDictionary *options = [NSDictionary dictionaryWithObject:NSHTMLTextDocumentType forKey:NSDocumentTypeDocumentAttribute];
    NSString *ha = [NSString stringWithFormat:@"总共 <font color=\"0x4794EF\">%d</font> 件", (int)count];
    NSAttributedString * aa = [[NSAttributedString alloc] initWithData:[ha dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil];
    [self.countView setAttributedText:aa];
    //
    NSString *hb = [NSString stringWithFormat:@"折后 <font color=\"0x4794EF\">￥%0.2f</font>", price];
    NSAttributedString * ab = [[NSAttributedString alloc] initWithData:[hb dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil];
    [self.priceView setAttributedText:ab];
    [self.tableView reloadData];
    //
    __weak ProductListCtrl *blockSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        [self.view setAlpha:1];
    } completion:^(BOOL finished) {
        [blockSelf.rightLayout setConstant:0];
        [blockSelf.view updateConstraintsIfNeeded];
        [UIView beginAnimations:nil context:nil];
        [blockSelf.view layoutIfNeeded];
        [UIView commitAnimations];
    }];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    if ([[touches anyObject] view] == self.view) {
        [self.rightLayout setConstant:-334];
        [self.view updateConstraintsIfNeeded];
        //
        __weak ProductListCtrl *blockSelf = self;
        [UIView animateWithDuration:0.2 animations:^{
            [blockSelf.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.2 animations:^{
                [blockSelf.view setAlpha:0];
            } completion:^(BOOL finished) {
                [blockSelf dismissViewControllerAnimated:NO completion:nil];
            }];
        }];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *item = [self.data objectAtIndex:indexPath.row];
    NSMutableArray *materials = [NSMutableArray array];
    for (id temp in  [[[item objectForKey:@"model_info"] objectForKey:@"model"] objectForKey:@"material"]) {
        [materials addObject:[temp objectForKey:@"materialname"]];
    }
    //
    ProductListCtrlCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
    [cell.countView setText:[AppData countToString:[item objectForKey:@"count"] lable:nil]];
    [cell.nameView setText:[AppData objToString:[item objectForKey:@"productname"] lable:nil]];
    [cell.sizeView setText:[AppData sizeToString:[item objectForKey:@"size"] lable:@"规格："]];
    [cell.otherView setText:[AppData objToString:[materials componentsJoinedByString:@","] lable:@"材质："]];
    [AppData loadImage:[item objectForKey:@"thumb400_jpg"] view:cell.iconView];
    return cell;
}
-(void)addCartTouch:(id)sender {
    NSDictionary *client = [TMGlobal valueForKey:@"client"];
    if(client && [AppData userAddCart:self.data client:client]){
        [TMAlert showAtView:self.view image:@"img_Prompt_ShoppingCar_OK.png"];
    }
}
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if ([TMGlobal valueForKey:@"client"]) {
        if ([identifier isEqualToString:@"cartSegue"]) {
            [self addCartTouch:sender];
        }
        return NO;
    }
    return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __weak ProductListCtrl *this = self;
    if ([segue.destinationViewController isKindOfClass:ProductDetailCtrl.class]) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        if (indexPath) {
            ProductDetailCtrl *ctrl = segue.destinationViewController;
            [ctrl setData:[self.data objectAtIndex:indexPath.row]];
        }
    }
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:UserCenterSelect.class]) {
            UserCenterSelect *root = [ctrl.viewControllers firstObject];
            [root setOnSelected:^(id target, id result){
                [ctrl dismissViewControllerAnimated:YES completion:^{
                    if ([segue.identifier isEqualToString:@"cartSegue"]) {
                        [this addCartTouch:sender];
                    }
                }];
            }];
        }
    }
}
@end


#pragma mark -
#pragma mark ProductCenterCell
@implementation ProductCenterCell
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self.layer setMasksToBounds:YES];
        [self.layer setCornerRadius:4];
    }
    return self;
}
- (void)awakeFromNib{
    [super awakeFromNib];
    if (self.selectView) {
        [self.selectView setHidden:YES];
    }
    [self setType:self.type];
}
- (void)setSelected:(BOOL)selected{
    [super setSelected:selected];
    [self.selectView setSelected:selected];
}
- (void)setType:(NSInteger)type{
    _type = type;
    if (self.infoView) {
        [self.infoView setHidden:type != 2];
    }
}
@end


#pragma mark -
#pragma mark ProductCenterCtrl
@implementation ProductCenterCtrl
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTipsView:[[ProductClassifyTips alloc] initWithFrame:CGRectZero]];
    //
    [self.collectionView.headerView addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.headerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.headerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.headerView setTitle:@"下拉刷新" forState:TMRefreshStateNormal];
    //
    [self.collectionView.footerView addTarget:self action:@selector(footerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.collectionView.footerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.collectionView.footerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.collectionView.footerView setTitle:@"上拉翻页" forState:TMRefreshStateNormal];
    //
    [self.classifyView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.screenView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    //
    [self.mixedView addTarget:self action:@selector(sortTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.salesView addTarget:self action:@selector(sortTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.priceView addTarget:self action:@selector(sortTouch:) forControlEvents:UIControlEventTouchUpInside];
    //
    [self hiddenLeft:NO];
    [self addGestureRecognizer];
    //
    self.menuView.currentTitle = @"产品";
    [self.menuView.textField setDelegate:self];
    [self.menuView.clearbtn addTarget:self action:@selector(clearTouch:) forControlEvents:UIControlEventTouchUpInside];
    //
    [self setType:self.type];
    [self headerRefresh:nil];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (isEmpty(textField.text)) {
        [self.condition setValue:nil forKey:@"keyword"];
    }else{
        [self.condition setValue:textField.text forKey:@"keyword"];
    }
    [self headerRefresh:nil];
    return YES;
}
-(void)clearTouch:(UIButton *)sender{
    [self.condition setValue:nil forKey:@"keyword"];
    [self headerRefresh:nil];
}
- (void)setType:(NSInteger)type{
    _type = type;
    if (type == 0) {
        [self.exitView setSelected:NO];
    }else{
        [self.exitView setSelected:YES];
    }
}
- (void)sortTouch:(UIButton*)sender{
    //|=%7C
    if (sender==self.priceView) {
        [self.mixedView setSelected:NO];
        [self.salesView setSelected:NO];
        
        if (self.priceView.selected == YES) {
            [self.priceView setSort:!self.priceView.sort];
        }else{
            [self.priceView setSelected:YES];
            [self.priceView setSort:NO];
        }
        if (self.priceView.sort) {
            [self.condition setValue:@"price|desc" forKey:@"sort"];
        }else{
            [self.condition setValue:@"price|asc" forKey:@"sort"];
        }
    }else{
        [self.priceView setSelected:NO];
        [self.mixedView setSelected:NO];
        [self.salesView setSelected:NO];
        [sender setSelected:YES];
        //
        [self.condition setValue:@"" forKey:@"spacearea"];
        if (sender == self.salesView) {
            [self.condition setValue:@"hots|asc" forKey:@"sort"];
        }else{
            [self.condition setValue:@"id|asc" forKey:@"sort"];
        }
    }
    [self headerRefresh:nil];
}
-(void)reloadData{
    [self headerRefresh:nil];
}
- (void)headerRefresh:(TMRefresh*)sender{
    if (sender == nil) {
        sender = self.collectionView.headerView;
        [sender beginRefreshing];
    }
    //
    __weak ProductCenterCtrl *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this.condition setValue:@(1) forKey:@"page"];
        [this setData:[AppData productList:this.condition]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender endRefreshing];
            [self.nullView setHidden:[this.data count]>0];
            [this.collectionView.footerView setFinish:NO];
            //
            [this.collectionView reloadData];
        });
    });
}
- (void)footerRefresh:(TMRefresh*)sender{
    __weak ProductCenterCtrl *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSInteger p = [[this.condition objectForKey:@"page"] intValue] + 1;
        [this.condition setValue:@(p) forKey:@"page"];
        //
        NSArray *app = [AppData productList:this.condition];
        [this.data addObjectsFromArray:app];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender setFinish:[app count]==0];
            [sender endRefreshing];
            //
            [this.collectionView reloadData];
        });
    });
}
- (void)hiddenLeft:(BOOL)animation{
    [self.leftLayout setConstant:-250];
    [self.view setNeedsUpdateConstraints];
    if (animation) {
        [UIView beginAnimations:nil context:nil];
        [self.view layoutIfNeeded];
        [UIView commitAnimations];
    }
}
- (void)showLeft:(BOOL)animation{
    [self.leftLayout setConstant:0];
    [self.view setNeedsUpdateConstraints];
    if (animation) {
        [UIView beginAnimations:nil context:nil];
        [self.view layoutIfNeeded];
        [UIView commitAnimations];
    }
}
- (IBAction)exitTouch:(UIButton*)sender {
    if (sender.selected) {
        if (self.navigationController) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }else{
        IndexHomeCtrl *tabbar = (id)self.splitViewController;
        if ([tabbar isKindOfClass:IndexHomeCtrl.class]) {
            [tabbar showMenu];
        }
    }
}
- (void)ctrlTouch:(UIButton*)sender{
    if (sender.selected) {
        [sender setSelected:NO];
        if (self.classifyView.selected == NO && self.screenView.selected == NO) {
            [self hiddenLeft:YES];
        }
    }else{
        [self.classifyView setSelected:NO];
        [self.screenView setSelected:NO];
        [sender setSelected:YES];
        [self showLeft:YES];
    }
    //
    for (uint i = 0; i < self.childViewControllers.count; i++) {
        UIViewController *ctrl  = [self.childViewControllers objectAtIndex:i];
        if (self.classifyView.selected != i || self.screenView.selected == i) {
            [ctrl.view.superview setHidden:NO];
        }else{
            [ctrl.view.superview setHidden:YES];
        }
    }
}
//
- (NSMutableDictionary *)condition{
    if (_condition == nil) {
        [self setCondition:[NSMutableDictionary dictionary]];
    }
    [_condition setValue:@(50) forKey:@"limit"];
    return _condition;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.data count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ProductCenterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    if (indexPath.item<[self.data count]) {
        NSDictionary *item = [self.data objectAtIndex:indexPath.item];
        [cell.titieView setText:[AppData objToString:[item objectForKey:@"productname"] lable:nil]];
        [cell.priceView setText:[AppData priceToString:[item objectForKey:@"price"] lable:nil]];
        [AppData loadImage:[item objectForKey:@"thumb400_jpg"] view:cell.imageView];
        [cell setType:self.type];
    }
    return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [scrollView setNeedsLayout];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [scrollView setNeedsLayout];
}
//
- (id)findCell:(UIView*)view{
    UIView *temp = view;
    while (temp) {
        if ([temp isKindOfClass:UICollectionViewCell.class]) {
            return temp;
        }
        temp = temp.superview;
    }
    return nil;
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(nullable id)sender{
    //顶部导航
    if ([TMGlobal valueForKey:@"client"]) {
        if ([identifier isEqualToString:@"favorite"]) {
            [TMGlobal setValue:@(3) forKey:@"clientTag"];
            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
             return NO;
        }
        if ([identifier isEqualToString:@"cart"]) {
            [TMGlobal setValue:@(4) forKey:@"clientTag"];
            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
             return NO;
        }
        if ([identifier isEqualToString:@"client"]) {
            [TMGlobal setValue:nil forKey:@"clientTag"];
            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
            return NO;
        }
    }     
    //
    if(self.type == 2 && [sender isKindOfClass:UICollectionViewCell.class]){
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
        if (indexPath && self.onSelected){
            self.onSelected(self, [self.data objectAtIndex:indexPath.item]);
        }
        return NO;
    }
    return YES;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender{
    //顶部导航
    __weak ProductCenterCtrl *this = self;
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *ctrl = segue.destinationViewController;
        if ([[ctrl.viewControllers firstObject] isKindOfClass:UserCenterSelect.class]) {
            UserCenterSelect *root = [ctrl.viewControllers firstObject];
            [root setOnSelected:^(id target, id result){
                [this dismissViewControllerAnimated:YES completion:^{
                    if(result){
                        if([segue.identifier isEqualToString:@"favorite"]){
                            [TMGlobal setValue:@(3) forKey:@"clientTag"];
                            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
                        }
                        if([segue.identifier isEqualToString:@"cart"]){
                            [TMGlobal setValue:@(4) forKey:@"clientTag"];
                            [TMGlobal setValue:@(8) forKey:@"homeIndex"];
                        }
                    }
                }];
            }];
            return;
        }
        if ([[ctrl.viewControllers firstObject] isKindOfClass:ProductSynopsisCtrl.class]) {
            UICollectionViewCell *cell = [self findCell:sender];
            if (cell) {
                NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
                if (cell) {
                    ProductSynopsisCtrl *root = [ctrl.viewControllers firstObject];
                    [root setData:[self.data objectAtIndex:indexPath.item]];
                }
            }
            return;
        }
    }
    //详细
    if ([sender isKindOfClass:UICollectionViewCell.class]) {
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:sender];
        if (indexPath) {
            ProductDetailCtrl *detail = segue.destinationViewController;
            if ([detail isKindOfClass:ProductDetailCtrl.class]) {
                [detail setData:[this.data objectAtIndex:indexPath.item]];
                [detail setOnSelected:this.onSelected];
                [detail setSource:this.data];
                [detail setType:this.type];
            }
        }
        return;
    }
    //分类
    __weak UINavigationController *root = segue.destinationViewController;
    if ([segue.identifier isEqualToString:@"ProductClassify"]) {
        __weak ProductClassifyCtrl *classify = [root.viewControllers firstObject];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [classify setData:[AppData productClassify]];
            [classify setTitle:[classify.data objectForKey:@"name"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [classify.tableView reloadData];
            });
        });
        [classify setType:0];
        [classify setOnSelected:^(id sender, id result){
            if ([sender isKindOfClass:NSIndexPath.class]) {
                if ([result objectForKey:@"child"]) {
                    ProductClassifyCtrl *next = [this.storyboard instantiateViewControllerWithIdentifier:@"ProductClassify"];
                    [root pushViewController:next animated:YES];
                    [next setOnSelected:classify.onSelected];
                    [next setData:result];
                }
                [this.condition setValue:[result objectForKey:@"id"] forKey:@"cateid"];
                [this headerRefresh:nil];
            }
        }];
        return;
    }
    //筛选
    if ([segue.identifier isEqualToString:@"ProductScreen"]) {
        __weak ProductClassifyCtrl *screen = [root.viewControllers firstObject];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [screen setData:[AppData productScreen]];
            [screen setTitle:[screen.data objectForKey:@"name"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [screen.tableView reloadData];
            });
        });
        [screen setType:1];
        [screen setOnSelected:^(id sender, id result){
            if (sender == nil && result==nil) {
                NSArray *ids = [NSArray arrayWithObjects:@(0), @(1), @(2), @(3), nil];
                NSArray *keys = [NSArray arrayWithObjects:@"styleid", @"spaceid", @"processingid", @"colorid", nil];
                for (id key in keys) {
                    [this.condition setValue:nil forKey:key];
                }
                for (id group in screen.tips.allKeys) {
                    NSDictionary *value = [screen.tips objectForKey:group];
                    for (id item in value.allKeys) {
                        NSInteger i = [ids indexOfObject:[[value objectForKey:item] objectForKey:@"parentid"]];
                        if (i != NSNotFound) {
                            id key = [keys objectAtIndex:i];
                            [this.condition setValue:[value.allKeys componentsJoinedByString:@","] forKey:key];
                        }
                        break;
                    }
                }
                [this.tipsView reloadTips];
                [this headerRefresh:nil];
            }else{
                CGRect rect = [root.view convertRect:root.view.bounds toView:this.view];
                [this.tipsView showFromRect:CGRectOffset(rect, rect.size.width, 0) atView:this.view];
                [this.tipsView setTips:screen.tips];
                [this.tipsView setData:result];
                [this.tipsView reloadTips];
                [this.tipsView setOnSelected:^(id sender, id result){
                    if (result) {
                        [screen setTips:result];
                        [screen reloadTips];
                        screen.onSelected(nil, nil);
                    }
                }];
            }
        }];
        return;
    }
}
-(NSString*)getstr:(NSMutableString *)str temp:(id)temp{
    NSRange range = [str rangeOfString:temp];
    if(range.location<str.length){
        [str deleteCharactersInRange:range];
        NSArray *listItems = [str componentsSeparatedByString:@","];
        NSMutableArray *arr = [[NSMutableArray alloc]init];
        for(id item in listItems){
            if(![item isEqualToString:@""]){
                [arr addObject:item];
                
            }
        }
        if([arr count]==1){
            return [NSString stringWithFormat:@"%@",[arr objectAtIndex:0]];
        }
        return [arr componentsJoinedByString:@","];
    }
    return nil;
}
//
-(void)addGestureRecognizer{
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] init];
    [swipeLeft addTarget:self action:@selector(gestureRecognizerHandle:)];
    [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.collectionView addGestureRecognizer:swipeLeft];
    
    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] init];
    [swipeRight addTarget:self action:@selector(gestureRecognizerHandle:)];
    [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.collectionView addGestureRecognizer:swipeRight];
}
-(void)gestureRecognizerHandle:(UISwipeGestureRecognizer*)sender{
    if (sender && sender.direction==UISwipeGestureRecognizerDirectionLeft){
        [self hiddenLeft:YES];
    }else{
        [self showLeft:YES];
    }
}
@end